package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.service.TestService;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service

public class TestServiceImpl implements TestService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    @SneakyThrows
    public void testLock() {
       RLock lock = redissonClient.getLock("lock");
        //加锁
//        lock.lock();
        //加锁带设置超时时间
        boolean b = lock.tryLock(7, TimeUnit.SECONDS);
        if (b){
            String num = stringRedisTemplate.opsForValue().get("num");
            if (num==null){
                return;
            }
            int nn = Integer.parseInt(num);
            System.out.println(nn);

            stringRedisTemplate.opsForValue().set("num",String.valueOf(++nn));
        lock.unlock();

        }else {
            Thread.sleep(100);

            testLock(); System.out.println("自旋");
        }

    }



























    /**
     * 单线程解决安全问题：上锁
     */
//    @Override
//    public synchronized void testLock() {
//        String num = stringRedisTemplate.opsForValue().get("num");
//        if (num==null){
//            return;
//        }
//        int nn = Integer.parseInt(num);
//        stringRedisTemplate.opsForValue().set("num",String.valueOf(++nn));
//    }
}
